package patrol.mobile.com.mobilepatrol.activity.culvert;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.CulvertTrackListAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.Handong;
import patrol.mobile.com.mobilepatrol.bean.Hddqjcb;
import patrol.mobile.com.mobilepatrol.bean.Hdjcxjcb;
import patrol.mobile.com.mobilepatrol.manager.HManager;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.persenter.QHUpPer;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.view.BridgeUpView;

import static patrol.mobile.com.mobilepatrol.R.mipmap.upload;

/**
 * Created by apple on 17/9/29.
 */

public class CulvertListActivity extends BaseActivity implements BridgeUpView{
    @BindView(R.id.iv_end_title)
    ImageView iv_end_title;
    @BindView(R.id.recycler)
    public RecyclerView recyclerView;
//    @BindView(R.id.cb)
//    CheckBox cb_all;
    @BindView(R.id.iv)
    ImageView iv;
    boolean delAll;
    private CulvertTrackListAdapter mAdapter;
    private List<Handong> mList = new ArrayList<>();
    private List<Hddqjcb> hds_dq;
    private List<Hdjcxjcb> hds_jc;
    private List<String> uphdcodes;
    public boolean selAll;


    @Override
    public void initView() {
        //super的重要性
        super.initView();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new CulvertTrackListAdapter(this, mList);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mList = HManager.getHList();
        HManager.setcbState(mList,false);
        mAdapter.updateItems(mList);
    }

    @Override
    public void initData() {
        mList = HManager.getHList();
        HManager.setcbState(mList,false);
//        Logger.d(GsonUtil.GsonString(PatrolApp.realm.copyFromRealm(mList)));
        mAdapter.updateItems(mList);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(CulvertListActivity.this,true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("涵洞巡查");
        iv_end_title.setVisibility(View.VISIBLE);
        iv_end_title.setImageResource(R.mipmap.qrcode);
        iv_end_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(CulvertScanActivity.class);
                CommonUtil.openNewActivityAnim(CulvertListActivity.this, false);
            }
        });
        iv_right_title.setVisibility(View.VISIBLE);
        iv_right_title.setImageResource(upload);
        iv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 uphdcodes = mAdapter.gethdcodes();
                if (uphdcodes==null||uphdcodes.size()==0){
                    showToast("请选择涵洞");
                    return;
                }
//                showToast(uphdcodes.toString());
                List<Hddqjcb> upList_dq = new ArrayList<Hddqjcb>();
                List<Hdjcxjcb> upList_jc = new ArrayList<Hdjcxjcb>();
                //多少个涵洞
                for (int i=0;i<uphdcodes.size();i++){
                    //每个涵洞的定期检查列表
                    List<Hddqjcb> trans_dq = new ArrayList<Hddqjcb>();
                    List<Hdjcxjcb> trans_jc = new ArrayList<Hdjcxjcb>();
                     hds_dq  = HManager.getHDDQListNoUp(uphdcodes.get(i));
                     hds_jc  = HManager.getHDJCListNoUp(uphdcodes.get(i));
                    if (hds_dq!=null&&hds_dq.size()>0){
                        trans_dq = PatrolApp.realm.copyFromRealm(hds_dq);
                        upList_dq.addAll(trans_dq);
                    }
                    if (hds_jc!=null&&hds_jc.size()>0){
                        trans_jc = PatrolApp.realm.copyFromRealm(hds_jc);
                        upList_jc.addAll(trans_jc);
                    }

                }
                uploadDQ(upList_dq);
                uploadJC(upList_jc);
            }
        });

    }

    private void uploadJC(List<Hdjcxjcb> upList_jc) {
        if (upList_jc != null && upList_jc.size() > 0) {

            Map<String, Object> map = new TreeMap<String, Object>();
            /**
             * list转jsonarray
             * string转jsonarray
             */
            JsonArray jsonArray = new Gson().toJsonTree(upList_jc, new TypeToken<List<Hdjcxjcb>>() {
            }.getType()).getAsJsonArray();

            map.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
            map.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
            map.put("hdjcxjc", jsonArray);
            /**
             * map转json字符串
             */
            String obj2 = GsonUtil.GsonString(map);
            Logger.d(obj2);
            QHUpPer per = new QHUpPer(CulvertListActivity.this, obj2);
            per.up2(Urls.addHdjcxjc);

        } else {
            hideLoading();
            showToast("暂无经常检查列表");
        }
    }

    private void uploadDQ(List<Hddqjcb> upList_dq) {
        if (upList_dq != null && upList_dq.size() > 0) {

            Map<String, Object> map = new HashMap<String, Object>();
            /**
             * list转jsonarray
             * string转jsonarray
             */
//                    JsonArray jsonArray2 = new JsonParser().parse(upString).getAsJsonArray();
            JsonArray jsonArray = new Gson().toJsonTree(upList_dq, new TypeToken<List<Hddqjcb>>() {
            }.getType()).getAsJsonArray();

            map.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
            map.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
            map.put("hddqjc", jsonArray);
            /**
             * map转json字符串
             */
            String obj2 = GsonUtil.GsonString(map);
            Logger.d(obj2);
            QHUpPer per = new QHUpPer(CulvertListActivity.this, obj2);
            per.up2(Urls.addHdqjjc);

        } else {
            hideLoading();
            showToast("暂无定期检查列表");
        }
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.comment_list_all;
    }

    @Override
    public void setListener() {
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(CulvertListActivity.this, CulvertDetailActivity.class);
                intent.putExtra("list",true);
                intent.putExtra("hdcode",mList.get(position).hdcode);
                startActivity(intent);
                CommonUtil.openNewActivityAnim(CulvertListActivity.this,false);
            }
        });
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //原来是全选
                if (selAll){
                    unSel();
                }else{
                    selAll();
                }

            }
        });

    }
    public void selAll(){
        selAll = true;
        HManager.setcbState(mList,true);
        mList = HManager.getHList();
        mAdapter.updateItems(mList);
        iv.setImageResource(R.mipmap.sel);
    }
    public void unSel(){
        selAll = false;
        HManager.setcbState(mList,false);
        mList = HManager.getHList();
        mAdapter.updateItems(mList);
        iv.setImageResource(R.mipmap.unsel);
    }
    @Override
    public void onError(String s) {
        showToast(s);
    }

    @Override
    public void onSuccess(String s) {
        showToast(s);
        if (uphdcodes != null && uphdcodes.size() > 0) {
            for (int i = 0; i < uphdcodes.size(); i++) {
                List dqs = HManager.getHDDQListNoUp(uphdcodes.get(i));
                List jcs = HManager.getHDJCListNoUp(uphdcodes.get(i));
                if ((dqs!=null&&dqs.size()>0)||(jcs!=null&&jcs.size()>0)){
                    HManager.setHDUpState(uphdcodes.get(i), true);
                }

            }
        }
        if (hds_dq != null && hds_dq.size() > 0) {
            for (int i = 0; i < hds_dq.size(); i++) {
                HManager.setHDDQListUpState(hds_dq.get(i).hdcode, true);

            }

        }
        if (hds_jc != null && hds_jc.size() > 0) {
            for (int i = 0; i < hds_jc.size(); i++) {
                HManager.setHDJCListUpState(hds_jc.get(i).hdcode, true);

            }
        }

        mList = HManager.getHList();
        mAdapter.updateItems(mList);
    }
    //根据列表cb控制全选cb，只是ui上的变化
    public void num(int style,int b,String hdcode){
        switch (style){
            //加
            case 0:
                if (b==mList.size()){
                    iv.setImageResource(R.mipmap.sel);
                }
                break;
            //减
            case 1:
                iv.setImageResource(R.mipmap.unsel);
                break;
        }
    }
    public void specialUpdate(final int sytle, final int b, final String hdcode) {
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int b = msg.arg1;
                int style = msg.arg2;
                String hdcode = (String) msg.obj;
                num(style,b,hdcode);
            }
        };


        final Runnable r = new Runnable() {
            public void run() {
                Message msg = handler.obtainMessage();
                msg.arg1 = b;
                msg.obj = hdcode;
                msg.arg2 = sytle;
               handler.sendMessage(msg);
            }
        };
        handler.post(r);
    }

}
